import ast
from flask import jsonify, request
from collections import Counter

from apps.data import data_app
from model.user import Record, TenHyModel
from tools.hy_model import ClassHyModel
from apps import db
@data_app.route('/show_all', methods=['POST'])
def pie():
    records = Record.query.all()
    data_to_send = []

    for record in records:
        # 使用 ast.literal_eval 将字符串形式的列表转换为 Python 列表
        result_list = ast.literal_eval(record.result)
        occur_time_list = ast.literal_eval(record.occur_time)
        # 使用 Counter 计算每种情绪的次数
        emotion_counter = Counter(result_list)

        # 将记录添加到结果列表中，过滤掉 emotion 为 None 的数值
        data_to_send.append({
            'start_time': record.start_time.isoformat(),  # 将 datetime 转换为字符串格式
            'result': result_list,
            'occur_time': occur_time_list,
            'img_save_path': record.img_save_path,
            'emotion_counts': [{'emotion': emotion, 'count': count} for emotion, count in emotion_counter.items() if emotion is not None]
        })

    return jsonify(data_to_send), 200



@data_app.route('/show_single', methods=['POST'])
def show_single():
    start_time = request.json.get('start_time')

    record = Record.query.filter_by(start_time=start_time).first()
    tenHyModel = TenHyModel.query.filter_by(start_time=start_time).first()

    #获取第一次分析数据的回答
    fir_answer = ast.literal_eval(tenHyModel.message)[2]['Content']

    # 使用 ast.literal_eval 将字符串形式的列表转换为 Python 列表
    result_list = ast.literal_eval(record.result)
    occur_time_list = ast.literal_eval(record.occur_time)
    # 使用 Counter 计算每种情绪的次数
    emotion_counter = Counter(result_list)

    data_to_send = []
    # 将记录添加到结果列表中
    data_to_send.append({
        'start_time': record.start_time.isoformat(),  # 将 datetime 转换为字符串格式
        'result': result_list,
        'occur_time': occur_time_list,
        'img_save_path': record.img_save_path,
        'emotion_counts': [{'emotion': emotion, 'count': count} for emotion, count in emotion_counter.items() if emotion is not None],
        'fir_answer' : fir_answer
    })
    return jsonify(data_to_send), 200

@data_app.route('/chat', methods=['POST'])
def chat():
    start_time = request.json.get('start_time')
    question = request.json.get('question')
    print(start_time,question)

    tenHyModel = TenHyModel.query.filter_by(start_time=start_time).first()
    classhyModel = ClassHyModel()
    classhyModel.Message = ast.literal_eval(tenHyModel.message)
    answer = classhyModel.chat(question)
    tenHyModel.message = str(classhyModel.Message)
    try:
        db.session.commit()
    except:
        db.session.rollback()
        return jsonify({'error': '数据库操作失败'}), 500

    response = {
        'answer': answer,
        'start_time' : start_time
    }
    return jsonify(response),200


@data_app.route('/chat_history', methods=['POST'])
def chat_history():
    start_time = request.json.get('start_time')
    print(start_time)
    tenHyModel = TenHyModel.query.filter_by(start_time=start_time).first()

    if tenHyModel is None:
        return jsonify({'error': 'No record found for the given start_time'}), 404

    message = ast.literal_eval(tenHyModel.message)
    del message[:2]
    response = {
        'history': message
    }
    return jsonify(response), 200
